package com.core.zyyz.pcmc.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.core.common.exception.ServiceException;
import com.core.common.utils.SecurityUtils;
import com.core.common.utils.StringUtils;
import com.core.common.utils.bean.BeanValidators;
import com.core.system.service.ISysConfigService;
import com.core.zyyz.pcmc.domain.PcmcDept;
import com.core.zyyz.pcmc.domain.PcmcRole;
import com.core.zyyz.pcmc.domain.PcmcRoleUser;
import com.core.zyyz.pcmc.mapper.PcmcRoleUserMapper;
import com.core.zyyz.pcmc.mapper.PcmcUserMapper;
import com.core.zyyz.pcmc.domain.PcmcUser;
import com.core.zyyz.pcmc.service.PcmcUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;

/**
 * 用户Service业务层处理
 *
 * @author core
 * @date 2024-10-15
 */
@Service
@Transactional
public class PcmcUserServiceImpl implements PcmcUserService {

    private static final Logger log = LoggerFactory.getLogger(PcmcUserServiceImpl.class);

    @Autowired
    private PcmcUserMapper pcmcUserMapper;
    @Autowired
    private PcmcRoleUserMapper pcmcRoleUserMapper;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    protected Validator validator;

    /**
     * 查询用户
     *
     * @param userCode 用户主键
     * @return 用户
     */
    @Override
    public PcmcUser selectPcmcUserByUserCode(String userCode) {
        return pcmcUserMapper.selectPcmcUserByUserCode(userCode);
    }

    /**
     * 查询用户列表
     *
     * @param pcmcUser 用户
     * @return 用户
     */
    @Override
    public List<PcmcUser> selectPcmcUserList(PcmcUser pcmcUser) {
        return pcmcUserMapper.selectPcmcUserList(pcmcUser);
    }

    /**
     * 新增用户
     *
     * @param pcmcUser 用户
     * @return 结果
     */
    @Override
    public int insertPcmcUser(PcmcUser pcmcUser) throws Exception {
        PcmcUser user = pcmcUserMapper.selectPcmcUserByUserCode(pcmcUser.getUserCode());
        if (user != null){
            throw new Exception("用户编号已存在！");
        }else {
            pcmcUser.setEmployeeCode(pcmcUser.getUserCode());
            return pcmcUserMapper.insertPcmcUser(pcmcUser);
        }
    }

    /**
     * 修改用户
     *
     * @param pcmcUser 用户
     * @return 结果
     */
    @Override
    public int updatePcmcUser(PcmcUser pcmcUser) {
        return pcmcUserMapper.updatePcmcUser(pcmcUser);
    }

    /**
     * 批量删除用户
     *
     * @param userCodes 需要删除的用户主键
     * @return 结果
     */
    @Override
    public int deletePcmcUserByUserCodes(String[] userCodes) {
        return pcmcUserMapper.deletePcmcUserByUserCodes(userCodes);
    }

    /**
     * 删除用户信息
     *
     * @param userCode 用户主键
     * @return 结果
     */
    @Override
    public int deletePcmcUserByUserCode(String userCode) {
        return pcmcUserMapper.deletePcmcUserByUserCode(userCode);
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(PcmcUser user) {
        return pcmcUserMapper.updatePcmcUser(user);
    }

    /**
     * 查询角色未授权用户
     * @param param
     * @return
     */
    public  List<PcmcRole> queryUserUnGrantRoleList() {
        List<PcmcRole> pcmcUserVos = pcmcRoleUserMapper.queryUserUnGrantRoleList();

        return pcmcUserVos;
    }

    /**
     * 查询角色已授权用户
     * @param param
     * @return
     */
    public  List<PcmcRole> queryUserGrantRoleList(PcmcRole param) {
        return pcmcRoleUserMapper.queryUserGrantRoleList(param);
    }

    /**
     * 用户授权角色
     *
     * @param pcmcRoleUser
     */
    @Override
    @Transactional
    public void insertUserAuth(PcmcRoleUser pcmcRoleUser) {
        String userCode = pcmcRoleUser.getUserCode();
        String[] roleCodes = pcmcRoleUser.getRoleCodes();
        pcmcRoleUserMapper.deleteUserRoleByUserCode(userCode);
//        PcmcUser user = (PcmcUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (StringUtils.isNotEmpty(roleCodes)) {
            // 新增用户与角色管理
            List<PcmcRoleUser> list = new ArrayList<PcmcRoleUser>(roleCodes.length);
            for (String roleCode : roleCodes) {
                PcmcRoleUser roleUser = new PcmcRoleUser();
                roleUser.setUserCode(userCode);
                roleUser.setRoleCode(roleCode);
                roleUser.setCreateBy("admin");
                roleUser.setCreateDate(new Date());
                roleUser.setLastUpdateBy("admin");
                roleUser.setLastUpdateDate(new Date());
                list.add(roleUser);
            }
            pcmcRoleUserMapper.batchRoleUser(list);
        }
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<PcmcUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (PcmcUser user : userList) {
            try {
                // 验证是否存在这个用户
                PcmcUser u = pcmcUserMapper.selectPcmcUserByUserCode(user.getUserCode());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    String password = configService.selectConfigByKey("sys.user.initPassword");
                    user.setUserPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    pcmcUserMapper.insertPcmcUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    user.setUserCode(u.getUserCode());
                    user.setLastUpdateBy(operName);
                    pcmcUserMapper.updatePcmcUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                }
                else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    public Map<String, String> queryEmployeeNameMap(List<String> deptCodeList) {
        List<PcmcUser> deptList = pcmcUserMapper.queryEmployeeNameMap(deptCodeList.toArray(new String[0]));
        return CollectionUtils.isEmpty(deptList) ? null : (Map<String, String>)deptList.stream().collect(Collectors.toMap(PcmcUser::getUserCode, PcmcUser::getUserName));
    }
}
